<!-- AddContract -->
<template>
  <div class="app-container">
    <div v-show="submitType===1" class="mb-3">{{signType == 0?'新增签约':'新增电子签约'}}</div>
    <el-form ref="form" :model="form" label-width="100px" size="small">
      <el-form-item label="" v-if="submitType===1">
        <el-select v-model="value" filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading" @change="onChange">
          <el-option v-for="(item,index) in options" :key="item.id" :label="item.name" :value="index">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户id">
        <el-input readonly v-model="form.customerId"></el-input>
      </el-form-item>
      <el-form-item label="客户姓名">
        <el-input readonly v-model="name"></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input readonly v-model="mobile"></el-input>
      </el-form-item>
      <!-- <el-form-item label="合同编号">
        <el-input v-model="form.contractCode"></el-input>
      </el-form-item> -->
      <el-form-item label="签约额度" prop="deposit">
        <el-input type="number" v-model="form.deposit" placeholder="请填写客户的需求金额"></el-input>
      </el-form-item>
      <!-- <el-form-item label="签约佣金">
        <el-input type="number" v-model="form.brokerage"></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="状态">
        <el-select v-model="form.state" placeholder="状态">
          <el-option label="初始" :value="0" />
          <el-option label="已签约" :value="1" />
          <el-option label="完件" :value="4" />
          <el-option label="作废" :value="5" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="备注">
        <el-input type="textarea" placeholder="请输入签约重要备注信息。。。" v-model="form.remark"></el-input>
      </el-form-item>
      <el-form-item label="签约产品">
        <div class="">
          <el-button type="primary" size="small" @click="openDialog()">添加签约产品</el-button>
        </div>
        <el-table class="el_table" :data="checkList" size="small" border>
          <el-table-column label="id" prop="id"></el-table-column>
          <el-table-column label="产品名称" prop="name"></el-table-column>
          <el-table-column label="产品备注" prop="remark"></el-table-column>
          <el-table-column label="进度" prop="process">
            <template slot-scope="{row}">{{PRODUCTPROCESSLIST[row.process||0]}}</template>
          </el-table-column>
          <el-table-column label="完成凭证" prop="">
            <template slot-scope="{row}">
              <el-image :src="row.certificate" :preview-src-list="[row.certificate]" v-if="row.certificate"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="操作" prop="">
            <template slot-scope="{row}">
              <el-link type="primary" size="mini" @click="openDialog(row)">编辑</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <!-- <el-form-item label="跟进资料">
        <div class="image_box">
          <div class="image_cell">
            <el-image :src="form.idcardFront" :preview-src-list="[form.idcardFront]"></el-image>
            <span class="name">身份证正面</span>
          </div>
          <div class="image_cell">
            <el-image :src="form.idcardBack" :preview-src-list="[form.idcardBack]"></el-image>
            <span class="name">身份证反面</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="必备资料" v-if="signType == 0">
        <div class="image_box">
          <div class="image_cell">
            <el-image :src="form.authorizeFile" :preview-src-list="[form.authorizeFile]"></el-image>
            <span class="name">授权书</span>
          </div>
          <div class="image_cell">
            <el-image :src="form.creditFile" :preview-src-list="[form.creditFile]"></el-image>
            <span class="name">征信报告</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="其他资料">
        <div class="image_box">
          <el-image v-for="(item,index) in showImage(form.otherFile)" :key="index" :src="item" :preview-src-list="showImage(form.otherFile)"></el-image>
        </div>
      </el-form-item>
      <el-form-item label="合约" v-if="signType == 0">
        <el-upload action="" list-type="picture-card" :file-list="fileList" :http-request="uploadFile" :on-success="successHandle" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item> -->

      <el-form-item label="待签合同文件" v-if="signType == 1">
        <el-upload action="" accept=".pdf" :file-list="fileList" :http-request="uploadFile" :on-success="successHandle" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

      <el-form-item label="客户签章位置" v-if="signType == 1">
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="addLine()">添加</el-button>
        <div class="" :key="randomKey">
          <div class="line_box" v-for="(item,index) in locations" :key="index">
            <div class="cell">
              <span>落章页码：</span>
              <el-input class="sort_input" v-model="item.page"></el-input>
            </div>
            <div class="cell">
              <span>X轴位置(cm)：</span>
              <el-input class="sort_input" v-model="item.x"></el-input>
            </div>
            <div class="cell">
              <span>Y轴位置(cm)：</span>
              <el-input class="sort_input" v-model="item.y"></el-input>
            </div>
            <div class="cell">
              <i class="el-icon-remove-outline el_icon" @click="removeLine(item)"></i>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="submitLoading" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!-- 添加产品弹框 开始 -->
    <glsx-dialog :show="showDialog" title="添加编辑签约产品" @close="closeDialog()">
      <div>
        <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="80px">
          <el-form-item label="产品" prop="id">
            <el-select v-model="addForm.id">
              <el-option v-for="(item,index) in productList" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" resize="none" v-model="addForm.remark"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveInfo">保存</el-button>
            <el-button type="default" @click="closeDialog()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </glsx-dialog>
    <!-- 添加产品弹框 end -->

  </div>
</template>

<script>
import { way } from "./config";
import {
  uploadFile,
  myCustomerAll,
  addContract,
  updateContract,
  GETALLPRODUCTLIST,
} from "@/api/customer";
import { SAVE_CONTRACT_ESIGN } from "@/http/customer";
import GlsxDialog from "@/components/Dialog";
import { deepClone, showToast, broadcast } from "@/utils/util";
import { PRODUCTPROCESSLIST } from "@/common/constants";
export default {
  name: "SignContract",
  props: {
    submitType: {
      type: Number,
      default: 1,
    },
    info: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  components: { GlsxDialog },
  data() {
    return {
      value: "",
      loading: false,
      form: {
        customerId: "",
        id: "",
        contractCode: "",
        costRate: "",
        deposit: "",
        way: "",
        state: "",
        remark: "",
      },
      options: [],
      way,
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      urlList: [],
      submitLoading: false,
      userInfo: {},
      addForm: {},
      addFormRules: {
        id: [{ required: true, message: "请选择产品", trigger: "change" }],
      },
      showDialog: false,
      productList: [],
      checkList: [],
      PRODUCTPROCESSLIST,
      signType: 0, // 1 电子签约，0：普通签约
      randomKey: "",
      locations: [],
      mobile: "",
      name: "",
    };
  },
  computed: {},
  watch: {
    info: {
      handler: function (n, o) {
        let _this = this;
        let query = this.info;
        if (query.id) {
          this.remoteMethod(query.name).then((list) => {
            //let list = _this.options;
            console.log("test", list);
            let mn = list.find(
              (k) => k.name == query.name && k.mobile == query.mobile
            );
            console.log(mn);
            if (mn) {
              _this.setData(mn);
            }
          });
        }
        this.signType = query.type || 0;
        this.mobile = query.mobile;
        this.name = query.name;
        this.$set(this.form, "customerId", query.id);
      },
      immediate: true,
    },
  },
  created() {
    // let _this = this;
    // let query = this.info;
    // console.log(query);
    // if (query.id) {
    //   this.remoteMethod(query.name).then((list) => {
    //     console.log("test", list);
    //     let o = list.find(
    //       (k) => k.name == query.name && k.mobile == query.mobile
    //     );
    //     console.log(o);
    //     if (o) {
    //       _this.setData(o);
    //     }
    //   });
    // }
    // this.signType = query.type || 0;
    // this.mobile = query.mobile;
    // this.name = query.name;
  },
  mounted() {
    this.getProduct();
  },
  methods: {
    remoteMethod(query) {
      let _this = this;
      _this.loading = true;
      return new Promise((resolve, reject) => {
        let params = { name: query, mobile: query };
        myCustomerAll(params).then((res) => {
          _this.loading = false;
          let list = res.data || [];
          _this.options = list;
          resolve(list);
        });
      });
      // this.loading = true;
      // try {
      //   const params = {
      //     name: query,
      //     mobile: query,
      //   };
      //   myCustomerAll(params).then((res) => {
      //     let list = res.data || [];
      //     this.options = list;
      //   });
      //   this.loading = false;
      // } catch (error) {
      //   this.loading = false;
      // }
    },
    handleRemove(file, fileList) {
      this.urlList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadFile(params) {
      const data = new FormData();
      data.append("file", params.file);
      uploadFile(data, (progressEvent) => {
        const percent =
          ((progressEvent.loaded / progressEvent.total) * 100) | 0;
        params.onProgress({ percent: percent });
      }).then((res) => {
        res.url = res.data;
        params.onSuccess(res);
      });
    },
    successHandle(response, file, fileList) {
      this.urlList = fileList;
    },
    onChange(e) {
      const selectItem = this.options[e];
      this.form = selectItem;
      this.form.customerId = selectItem.id;
      this.name = selectItem.name;
      this.mobile = selectItem.mobile;
      this.userInfo = selectItem;
    },
    async onSubmit() {
      this.submitLoading = true;

      try {
        // this.form.images = this.urlList.map((element) => {
        //   if (element.response) {
        //     return element.response.data;
        //   } else if (element.url) {
        //     return element.url;
        //   }
        // });
        // this.form.images = this.form.images.join(",");

        // let oParams = deepClone(this.form);
        // let arr = [];
        // let m = this.checkList || [];
        // m.map((k) => {
        //   let o = {};
        //   o.productId = k.id;
        //   o.productName = k.name;
        //   o.certificate = k.certificate;
        //   o.remark = k.remark;
        //   arr.push(o);
        // });
        // oParams.productList = arr;
        let oParams = this.getParams();
        if (this.signType == 1) {
          this.saveElectronicEsign();
          return false;
        }

        if (this.submitType === 1) {
          await addContract(oParams).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message);
              //this.$router.back();
              broadcast("close.user.sign");
            }
          });
        } else {
          await updateContract(oParams).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.message);
              this.$emit("updateEvent");
              broadcast("close.user.sign");
            }
          });
        }

        this.submitLoading = false;
      } catch (error) {
        this.submitLoading = false;
      }
    },
    setData(form) {
      this.form.customerId = form.customerId || form.id;
      this.form.id = form.id;
      this.name = form.customerName || form.name;
      this.mobile = form.customerMobile || form.mobile;
      this.form.contractCode = form.contractCode;
      this.form.costRate = form.costRate;
      this.form.deposit = form.deposit;
      this.form.way = form.way;
      this.form.state = form.state;
      this.form.remark = form.remark;
      this.form.idcardFront = form.idcardFront;
      this.form.idcardBack = form.idcardBack;
      this.form.authorizeFile = form.authorizeFile;
      this.form.creditFile = form.creditFile;
      this.form.otherFile = form.otherFile;
      this.checkList = form.productList || [];
      this.form.locations = form.locations || [];
      console.log(form);
      if (typeof form.images == String) {
        const images = form.images ? form.images.split(",") : [];
        images.forEach((element) => {
          this.fileList.push({ name: "img", url: element });
          this.urlList.push({ name: "img", url: element });
        });
      } else {
        let arr = [];
        (form.images || []).map((k) => {
          arr.push({ name: k, url: k });
        });
        this.fileList = arr;
      }
      console.log(this.form);
    },

    // 展示图片
    showImage(str) {
      if (!str) {
        return false;
      }
      let arr = str.split(",");
      return arr;
    },

    // 获取所有产品
    getProduct() {
      GETALLPRODUCTLIST().then((res) => {
        this.productList = res.data || [];
      });
    },

    // 关闭弹框
    closeDialog() {
      this.showDialog = false;
      this.addForm = {};
    },

    // 打开弹框
    openDialog(row) {
      this.showDialog = true;
      if (row) {
        this.addForm = row;
      }
    },

    // 保存产品
    saveInfo() {
      let _this = this;
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        let oParams = deepClone(_this.addForm);
        //oParams.pid = Math.random()
        let list = _this.productList;
        let clist = _this.checkList || [];
        let o = list.find((k) => k.id == oParams.id);
        console.log(o);
        if (o) {
          oParams.name = o.name;
        }
        oParams.remark = oParams.remark;
        clist.push(oParams);
        console.log(clist);
        _this.closeDialog();
      });
    },

    // 添加客户签章
    addLine() {
      let o = {};
      let arr = this.locations || [];
      o.id = Math.random();
      arr.push(o);
      this.randomKey = Math.random();
      //this.form.locations.push(o);
    },

    // 删除客户签章
    removeLine(row) {
      let arr = this.locations || [];
      this.locations = arr.filter((k) => k.id != row.id);
    },

    // 保存电子签约
    saveElectronicEsign() {
      let oParams = this.getParams();
      let arr = [];
      let list = deepClone(this.locations);
      if (list && list.length > 0) {
        list.map((k) => {
          delete k.id;
          arr.push(k);
        });
      }
      oParams.locations = arr;
      SAVE_CONTRACT_ESIGN(oParams)
        .then((res) => {
          this.submitLoading = false;
          if (res.code === 200) {
            showToast({
              message: res.message,
              type: "success",
            });
            this.$router.back();
          }
        })
        .catch((error) => {
          this.submitLoading = false;
        });
    },

    // 获取提交参数
    getParams() {
      this.form.images = this.urlList.map((element) => {
        if (element.response) {
          return element.response.data;
        } else if (element.url) {
          return element.url;
        }
      });
      this.form.images = this.form.images.join(",");

      let oParams = deepClone(this.form);
      let arr = [];
      let m = this.checkList || [];
      m.map((k) => {
        let o = {};
        o.productId = k.id;
        o.productName = k.name;
        o.certificate = k.certificate;
        o.remark = k.remark;
        arr.push(o);
      });
      oParams.productList = arr;
      return oParams;
    },
  },
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.image_box {
  display: flex;
  .image_cell {
    display: flex;
    flex-direction: column;
    width: 120px;
    margin: 0 10px;
    .name {
      text-align: center;
      color: #999;
    }
  }
  .el-image {
    border: 1px dashed #ddd;
    padding: 4px;
    border-radius: 4px;
    width: 120px;
    height: 120px;
    box-sizing: border-box;
  }
}
.line_box {
  display: flex;
  align-items: center;
  margin: 10px 0;
  .cell {
    display: flex;
    align-items: center;
    margin-right: 20px;
    .sort_input {
      width: 80px;
    }
    .el_icon {
      font-size: 24px;
      color: #f00;
      cursor: pointer;
    }
    .el_icon:hover {
      opacity: 0.8;
    }
  }
}
</style>
